package han.chensing.latos.game.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

public class ByteDataStreamWriter {
    private final ByteArrayOutputStream byteArrayOutputStream;
    private final char[] module;
    private int moduleIndex;
    private int floatDivide;

    public ByteDataStreamWriter(char[] module) {
        this.byteArrayOutputStream=new ByteArrayOutputStream();
        this.module=module;
        this.moduleIndex=0;
        this.floatDivide=5;
    }

    public ByteDataStreamWriter(){
        this((char[])null);
    }

    public ByteDataStreamWriter(String module){
        this(module.toCharArray());
    }

    public void setFloatDivide(int floatDivide) {
        this.floatDivide = floatDivide;
    }

    public void writeInt(int i) throws IOException{
        byteArrayOutputStream.write(ByteUtil.intToBytes(i));
    }

    public void writeLong(long l) throws IOException{
        byteArrayOutputStream.write(ByteUtil.longToBytes(l));
    }

    public void writeByte(byte b) {
        byteArrayOutputStream.write(b);
    }

    public void writeShort(short s) throws IOException{
        byteArrayOutputStream.write(ByteUtil.shortToBytes(s));
    }

    public void writeFloat(float f) throws IOException{
        writeLong((long) (f*Math.pow(10,floatDivide)));
    }

    public void write(Object o) throws IOException{
        if (module==null)
            return;
        if (moduleIndex==module.length)
            return;
        char c = module[moduleIndex];
        writeAType(c,o);
        moduleIndex++;
    }

    public byte[] getByteArray(){
        return byteArrayOutputStream.toByteArray();
    }

    public void close() throws IOException{
        byteArrayOutputStream.close();
    }

    public void writeAType(char c,Object o) throws IOException{
        switch (c){
            case 'L':
            case 'l':
                writeLong((long) o);
                break;
            case 'f':
            case 'F':
                writeFloat((float) o);
                break;
            case 'i':
            case 'I':
                writeInt((int) o);
                break;
            case 's':
            case 'S':
                writeShort((short) o);
                break;
            case 'b':
            case 'B':
                writeByte((byte) o);
                break;
        }
    }
}
